from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.responses import PlainTextResponse
from .routes_qwen import router as qwen_router
from .routes_perception import router as perception_router
from .routes_decision import router as decision_router
from .routes_content import router as content_router
from .routes_announcements import router as announcements_router
from .routes_config import router as config_router
from .routes_params import router as params_router
from .routes_experiments import router as experiments_router
from .routes_events import router as events_router
from intelli_port.commons.config import load_settings
from intelli_port.commons.middleware import JavaSignatureMiddleware, CorrelationIdMiddleware, IdempotencyMiddleware
from intelli_port.commons.logging import json_logger


def create_app() -> FastAPI:
    app = FastAPI(title="Intelli Port API")
    s = load_settings()
    app.add_middleware(CorrelationIdMiddleware)
    app.add_middleware(JavaSignatureMiddleware, secret=s.java_signature_secret)
    app.add_middleware(IdempotencyMiddleware)

    logger = json_logger()

    @app.middleware("http")
    async def metrics_middleware(request: Request, call_next):
        resp = await call_next(request)
        logger.info("http.request", extra={"req_id": request.headers.get("x-request-id", ""), "corr_id": request.headers.get("x-correlation-id", ""), "service": "api"})
        return resp

    app.include_router(qwen_router, prefix="/qwen", tags=["qwen"])
    app.include_router(perception_router, prefix="/perception", tags=["perception"])
    app.include_router(decision_router, prefix="/decision", tags=["decision"])
    app.include_router(content_router, prefix="/content", tags=["content"])
    app.include_router(announcements_router, prefix="/announcements", tags=["announcements"])
    app.include_router(config_router, prefix="/config", tags=["config"])
    app.include_router(params_router, prefix="/params", tags=["params"])
    app.include_router(experiments_router, prefix="/experiments", tags=["experiments"])
    app.include_router(events_router, prefix="/events", tags=["events"])

    @app.get("/health")
    async def health():
        return JSONResponse({"ok": True})

    @app.get("/metrics")
    async def metrics():
        try:
            from prometheus_client import generate_latest
        except Exception:
            return PlainTextResponse("", media_type="text/plain; version=0.0.4")
        return PlainTextResponse(generate_latest(), media_type="text/plain; version=0.0.4")

    @app.get("/model/paths")
    async def model_paths():
        s = load_settings()
        return {
            "qwen_sft_data_dir": s.qwen_sft_data_dir,
            "qwen_output_dir": s.qwen_output_dir,
            "asr_finetune_data_dir": s.asr_finetune_data_dir,
            "tts_finetune_data_dir": s.tts_finetune_data_dir,
            "asr_output_dir": s.asr_output_dir,
            "tts_output_dir": s.tts_output_dir,
        }

    return app